package com.polaris.live.manager

import android.content.Context
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.AdjustThirdPartySharing
import com.adjust.sdk.LogLevel
import com.polaris.live.common.AppModule
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.ProdServerMode
import com.polaris.live.common.constant.ServerConfig
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.manager.withRetry
import com.polaris.live.common.network.EncryptHelper
import com.polaris.live.common.network.readEncryptKey2
import com.polaris.live.common.util.LogExt
import com.polaris.live.dialog.DmaData
import com.polaris.live.dialog.DmaDialog
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.UploadDeviceBean
import com.polaris.live.utils.DmaUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * AdJustManager
 *
 * @author Created by lucas on 2024/1/8 03:14
 */
object AdJustManager {

    private const val TAG = "--adjust"

    private const val ADJUST_TOKEN =
        "CtDo5dl36mdju2v1nw0vc6L5sVKD9QXlI0w/XIKrLXOIxbm9K+HAUqBGXz8a5E+i3NmSIEs3KZWUbWZ1dt4BcddC8dyAp0ZRDUgIuI4R7tvi1SoYPcOF0tCI5oGdSmZE7CWySNwPnc6yyjmA9UvAnO5Q/tnP4o/sh2kNxGro4gnD9LI5y3dzy+pz0UI6EMA/"
    @Volatile
    private var isInit = false

    /**
     * 初始化adjust
     */
    fun init(context: Context) {
        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            //如果是欧盟国家，先不初始化
            val dmaSelected = DmaUtils.getDmaSelected()
            if (dmaSelected == null && DmaUtils.isCurrentEEA()) {
                return@launch
            }

            init(context, DmaData(dmaSelected != null, dmaSelected ?: false))
        }
    }

    /**
     * 检查dma并初始化
     *
     * @return 是否需要弹窗，如果弹窗则需要暂停等待用户选择
     */
    fun checkDmaAndInit(context: Context, block: () -> Unit): Boolean {
        return DmaDialog.checkAndShowDmaDialog(context, {
            GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
                init(context, it)
            }

            block()
        })
    }

    /**
     * 初始化adjust
     */
    fun init(context: Context, dma: DmaData) {
        if (isInit) {
            return
        }
        isInit = true

        val appToken = EncryptHelper.decrypt(
            readEncryptKey2(ADJUST_TOKEN),
            ProdServerMode.encrypt,
            CommonConst.Adjust.PARAMETER
        )
        val environment = if (ServerConfig.isTestServer()) {
            AdjustConfig.ENVIRONMENT_SANDBOX
        } else {
            AdjustConfig.ENVIRONMENT_PRODUCTION
        }
        val config = AdjustConfig(context, appToken, environment)
        config.setLogLevel(LogLevel.INFO)

        config.setOnAttributionChangedListener { adjustAttribution ->
            uploadAdJust(adjustAttribution.adid, null)

            LogExt.logI(TAG) { "init adid " + adjustAttribution.adid }
        }

        Adjust.addSessionCallbackParameter(CommonConst.Adjust.UNIQUE_ID, AppModule.getUniqueDeviceId())
        Adjust.addSessionCallbackParameter(CommonConst.Adjust.ANDROID_ID, AppModule.getDeviceId())

        Adjust.addSessionCallbackParameter(CommonConst.Adjust.APP_TYPE, AppConst.APP_TYPE.toString())
        Adjust.addSessionCallbackParameter(CommonConst.Adjust.VARIANT_TYPE, AppConst.VARIANT_TYPE.toString())
        Adjust.addSessionCallbackParameter(CommonConst.Adjust.PLATFORM_TYPE, AppConst.PLATFORM_TYPE.toString())

        //欧盟dma
        val adjustThirdPartySharing = AdjustThirdPartySharing(null)
        adjustThirdPartySharing.addGranularOption("google_dma", "eea", if (dma.isEea) "1" else "0")
        adjustThirdPartySharing.addGranularOption(
            "google_dma",
            "ad_personalization",
            if (!dma.isEea || dma.confirm) "1" else "0"
        )
        adjustThirdPartySharing.addGranularOption(
            "google_dma",
            "ad_user_data",
            if (!dma.isEea || dma.confirm) "1" else "0"
        )
        Adjust.trackThirdPartySharing(adjustThirdPartySharing)

        Adjust.onCreate(config)

        LogExt.logI(TAG, "init adjust, isEea = ${dma.isEea}, dmaConfirm = ${dma.confirm}")
    }

    /**
     * 上传adjust数据
     */
    fun uploadAdJust(adid: String?, uniqueId: String?) {
        val finalUniqueId = uniqueId ?: AppModule.getUniqueDeviceId() ?: return
        val finalAdid = adid ?: Adjust.getAdid()?.apply {
            LogExt.logI(TAG) { "get adid $this" }
        } ?: return

        GlobalScope.launch(CoroutineScopeManager.defaultDispatcher) {
            withRetry(Int.MAX_VALUE, {
                if (it <= 1) {
                    0
                } else {
                    1000
                }
            }) {
                userService.uploadDeviceInfo(
                    UploadDeviceBean(
                        finalUniqueId,
                        finalAdid,
                        null,
                        AppModule.getDeviceId(),
                        AppConst.APP_TYPE,
                        AppConst.VARIANT_TYPE,
                        AppConst.PLATFORM_TYPE
                    )
                )
            }
        }
    }
}